<script setup lang='ts'>
import { onMounted, ref } from 'vue'
import type { OrderItem, OrderListParams } from '@/types/order'
import { getMemberOrderAPI, getRegistrationListByStatusAPI } from '@/services/order'
import type { OrderListDto } from '@/types/orderList'
import { onLoad } from '@dcloudio/uni-app'
import type { MyPage } from '@/types/global'
import { useMemberStore } from '@/stores'
import { getDeptListAPI } from '@/services/dept'; // 假设你已经封装好了调用后端的服务
import { getUserDelailsList } from '@/services/userDetails';

const deptList = ref<Map<number, string>>(new Map());
const fetchDeptList = async () => {
  try {
    const response = await getDeptListAPI();
    const deptData = response.data;
    console.log(deptData)
    deptData.forEach((dept: { deptId: number; deptName: string }) => {
      deptList.value.set(dept.deptId, dept.deptName);
    });
  } catch (error) {
    console.error('Failed to fetch department list', error);
  }
};
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 定义 porps
const props = defineProps<{
  orderState: string
}>()
const memberStore = useMemberStore()
const profile = memberStore.profile
// 请求参数
const queryParams: OrderListParams = {
  page: 1,
  pageSize: 5,
  orderState: props.orderState,
  patientId: profile?.patientId
};


// 获取订单列表
const orderList = ref<OrderListDto[]>([])
// 是否分页结束
// const isFinish = ref(false)
// 是否加载中标记，用于防止滚动触底触发多次请求
const isLoading = ref(false)
const getMemberOrderData = async () => {
  // 如果数据处于加载中，退出函数
  if (isLoading.value) return;

  // 发送请求前，标记为加载中
  isLoading.value = true;

  try {
    // 获取订单数据
    const res = await getRegistrationListByStatusAPI(queryParams);
    res.data.items = res.data.records;
    console.log(res.data.items);

    // 处理订单数据
    const orders = res.data.items as OrderListDto[];

    // 循环每个订单，获取用户信息（头像）
    for (const order of orders) {
      if (order.userId) {
        try {
          const userResponse = await getUserDelailsList(order.userId);
          order.user = userResponse.data; // 将用户信息赋值给订单项
        } catch (error) {
          console.error('Failed to fetch user details:', error);
        }
      }
    }

    // 将处理后的订单数据赋值给 orderList
    orderList.value = orders;
  } catch (error) {
    console.error('Failed to fetch order data', error);
  } finally {
    // 发送请求后，重置标记
    isLoading.value = false;
  }
};
onLoad(() => {
  getMemberOrderData()
  fetchDeptList();
})

// 订单支付
const onOrderPay = async (id: string) => {
  if (import.meta.env.DEV) {
    // 开发环境模拟支付
    // await getPayMockAPI({ orderId: id })
  } else {
    // #ifdef MP-WEIXIN
    // 正式环境支付：1.获取支付订单信息，2.调用微信支付API
    // const res = await getPayWxPayMiniPayAPI({ orderId: id })
    // await wx.requestPayment(res.result)
    // 注意：因小程序上线后被恶意投诉：理由为支付 0.01 元后不发货，现调整为模拟支付
    // await getPayMockAPI({ orderId: id })
    // #endif
  }
  // 成功提示
  uni.showToast({ title: '模拟支付成功' })
  // 模拟支付提示
  setTimeout(() => {
    wx.showModal({
      title: '温馨提示',
      content: '此交易是模拟支付，您并未付款，不会导致实际购买商品或服务',
      confirmText: '知道了',
      showCancel: false,
    })
  }, 2000)
  // 更新订单状态
  // const order = orderList.value.find((v) => v.id === id)
  // order!.orderState = OrderState.DaiFaHuo
}

// 是否分页结束
// const isFinish = ref(false)
// 是否触发下拉刷新
// const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开始动画
  // isTriggered.value = true
  // 重置数据
  queryParams.page = 1
  orderList.value = []
  // isFinish.value = false
  // 加载数据
  await getMemberOrderData()
  // 关闭动画
  // isTriggered.value = false
}
</script>

<template>
  <!-- 订单列表 -->
  <scroll-view scroll-y class='orders' refresher-enabled>
    <view class='card' v-for='item in orderList' :key='item.registration?.patientId'>
      <!-- 订单信息 -->
      <view class='status'>
        <text class='date'>
          {{ item.registration?.registrationId }}
        </text>
        <!-- 订单状态文字 -->
        <view>
          <text v-if='item.registration?.registrationStatus == 1'>待就诊</text>
          <text v-if='item.registration?.registrationStatus == 2'>就诊中</text>
          <text v-if='item.registration?.registrationStatus == 3'>就诊完成</text>
          <text v-if='item.registration?.registrationStatus == 4'>已退号</text>
          <text class='icon-delete'></text>
        </view>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <view class='orderItem'>
        <view class='right'>
          <view>挂号编号：{{ item?.registrationId }}</view>
          <view>医生名称：{{ item?.doctorName }}</view>
          <view>科室：{{ deptList.get(item?.deptId) || '未知科室' }}</view>
          <view>订单类型：{{ item?.schedulingType == 1 ? '门诊' : '急诊' }}</view>
          <view
          >预约时间：
            {{ item?.visitDate }}
            {{
              item?.subsectionType == 1
                ? '上午'
                : item?.subsectionType == 2
                  ? '下午'
                  : '晚上'
            }}
          </view>
        </view>
        <view class='left'>
          <text>医生头像</text>
          <image :src='item?.user?.picture'></image>
        </view>
      </view>

      <!-- 支付信息 -->
      <view class='payment' v-if='queryParams.orderState != 1'>
        <text>挂号金额</text>
        <text class='amount'>
          <text class='symbol'>¥</text>
          {{ item.registrationAmount }}
        </text>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view class='loading-text' :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ true ? '没有更多数据~' : '正在加载...' }}
    </view>
  </scroll-view>
</template>

<style lang='scss' scoped>
// 订单列表
.orders {
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .orderItem {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    margin: 20rpx 0;

    .left {
      flex: 3;

      image {
        margin-top: 20rpx;
        width: 125rpx;
        height: 125rpx;
      }
    }

    .right {
      flex: 9;

      .text {
        margin: 20rpx 0;
        font-size: 24rpx;
      }
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;

      image {
        width: 170rpx;
        height: 170rpx;
        border-radius: 50%;
      }
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
      border-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
